package com.jtpay.sdk.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.jtpay.sdk.R;
import com.jtpay.sdk.api.APIService;
import com.jtpay.sdk.model.PlatformInfo;
import com.jtpay.sdk.util.JFTMD5Utils;
import com.jtpay.sdk.util.JftConstants;
import com.jtpay.sdk.util.JftLogUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.jtpay.sdk.util.JftConstants.JUN_FU_TONG_URL_FORMAL;
import static com.jtpay.sdk.util.JftConstants.JUN_FU_TONG_URL_TEST;
import static com.jtpay.sdk.util.JftConstants.JUN_FU_TONG_URL_TIGER;

public class JftLoginActivity extends BaseActivity {
    private static final String TEST_INFO = "patch";
    private LinearLayout mSignInContainerLLayout;
    private EditText mUserNameEdt;
    private EditText mPasswordEdt;
    private Button mLoginBtn;
    private Button mFormalLoginBtn;
    private Button mTestLoginBtn;
    private ProgressDialog mProgressDialog;
    private Toast mToast;
    private CheckBox mRememberCheckBox;
    private CheckBox mAutoLoginCheckBox;
    private SharedPreferences mPreferences;
    private EditText mEtPort;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jft_login);
        initWidget();
        JftLogUtil.log(String.format("JftLoginActivity info = %s", TEST_INFO));
    }

    private void initWidget() {
        mSignInContainerLLayout = (LinearLayout) findViewById(R.id.layout_signin);
        LayoutInflater inflater = LayoutInflater.from(this);
        mSignInContainerLLayout.addView(inflater.inflate(R.layout.layout_custom_login, null));
        mUserNameEdt = (EditText) findViewById(R.id.edit_text_userName);
        mPasswordEdt = (EditText) findViewById(R.id.edit_text_password);
        mEtPort = (EditText) findViewById(R.id.et_port);

        mLoginBtn = (Button) findViewById(R.id.btn_login);
        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = JUN_FU_TONG_URL_TIGER + mEtPort.getText().toString() + File.separator;
                JftConstants.setURLConfig(url);
                login();
            }
        });
        mFormalLoginBtn = (Button) findViewById(R.id.btn_formal_login);
        mFormalLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JftConstants.setURLConfig(JUN_FU_TONG_URL_FORMAL);
                login();
            }
        });
        mTestLoginBtn = (Button) findViewById(R.id.btn_test_login);
        mTestLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JftConstants.setURLConfig(JUN_FU_TONG_URL_TEST);
                login();
            }
        });
        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);

        mRememberCheckBox = (CheckBox) findViewById(R.id.checkbox_remember_password);
        mAutoLoginCheckBox = (CheckBox) findViewById(R.id.checkbox_auto_login);
        boolean remember_password = mPreferences.getBoolean(getString(R.string.setting_remember_password), false);
        if (remember_password) {
            String userName = mPreferences.getString(getString(R.string.setting_name), "");
            String password = mPreferences.getString(getString(R.string.setting_password), "");
            if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)) {
                setNameAndPassword(userName, password);
            }
        } else {
            SharedPreferences.Editor editor = mPreferences.edit();
            editor.putString(getString(R.string.setting_name), "");
            editor.putString(getString(R.string.setting_password), "");
            editor.commit();
        }
        mRememberCheckBox.setChecked(remember_password);
        mRememberCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    String userName = mUserNameEdt.getText().toString();
                    String password = mPasswordEdt.getText().toString();
                    if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
                        showToast(getString(R.string.userNameOrPasswordTips));
                        mRememberCheckBox.setChecked(false);
                        return;
                    }
                    SharedPreferences.Editor editor = mPreferences.edit();
                    editor.putBoolean(getString(R.string.setting_remember_password), isChecked);
                    editor.putString(getString(R.string.setting_name), userName);
                    editor.putString(getString(R.string.setting_password), password);
                    editor.commit();
                } else {
                    SharedPreferences.Editor editor = mPreferences.edit();
                    editor.putBoolean(getString(R.string.setting_remember_password), isChecked);
                    editor.putString(getString(R.string.setting_name), "");
                    editor.putString(getString(R.string.setting_password), "");
                    editor.commit();
                }

            }
        });
    }

    private void dismissProgressDialog() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void showProgressDialog(String content) {
        if (null != mProgressDialog) {
            mProgressDialog.setMessage(content);
            mProgressDialog.show();
        }
    }

    private void login() {
        String userName = mUserNameEdt.getText().toString();
        String password = mPasswordEdt.getText().toString();
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
            showToast(getString(R.string.userNameOrPasswordTips));
            mUserNameEdt.requestFocus();
            return;
        }

        doLogin(userName, password);
    }

    private void showToast(String content) {
        if (null != mToast) {
            mToast.setText(content);
            mToast.show();
        }
    }

    private void doLogin(String userName, String password) {
        hideSoftInputMethod();
        showProgressDialog(getString(R.string.logining));
        password = JFTMD5Utils.getMD5(password).toLowerCase();
        StringBuilder sb = new StringBuilder(JftConstants.JUN_FU_TONG_URL_LOGIN);
        OkHttpClient newClient = new OkHttpClient.Builder().connectTimeout(JftConstants.TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(JftConstants.TIME_OUT, TimeUnit.SECONDS).build();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(sb.toString()).client(newClient).addConverterFactory(GsonConverterFactory.create()).build();
        APIService apiService = retrofit.create(APIService.class);
        Call<ResponseBody> call = apiService.login(userName, password);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                dismissProgressDialog();
                if (response.isSuccessful()) {
                    try {
                        String result = response.body().string();
                        JftLogUtil.log("doLogin result = " + result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String flag = jsonObject.getString("flag");
                            if ("1".equals(flag)) {
                                JSONArray platform = jsonObject.getJSONArray("msg");
                                int arraySize = platform.length();
                                ArrayList<PlatformInfo> list = new ArrayList<>(arraySize);
                                for (int i = 0; i < arraySize; i++) {
                                    JSONObject object = platform.getJSONObject(i);
                                    String name = object.getString("sysName");
                                    String userCode = object.getString("Business_No");
                                    String comKey = object.getString("Compkey");
                                    PlatformInfo info = new PlatformInfo(name, userCode, comKey);
                                    list.add(info);
                                }
                                startActivity(list);
                            } else {
                                loginFailed();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                dismissProgressDialog();
                loginFailed();
            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            if (1 == what) {
                mUserNameEdt.requestFocus();
                String content = (String) msg.obj;
                showToast(content);
            }
        }
    };

    private void hideSoftInputMethod() {
        InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(mLoginBtn.getWindowToken(), 0);
    }

    private void loginFailed() {
        Message message = Message.obtain();
        message.what = 1;
        message.obj = getString(R.string.login_failed);
        mHandler.sendMessage(message);
    }

    private void startActivity(ArrayList<PlatformInfo> infos) {
        Intent intent = new Intent(JftLoginActivity.this, JftPlatformsActivity.class);
        intent.putExtra(JftConstants.JUN_FU_TONG_PLAT_FORM_KEY, infos);
        startActivity(intent);
    }

    private void setNameAndPassword(String name, String password) {
        mUserNameEdt.setText(name);
        mPasswordEdt.setText(password);
    }
}
